/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SessionBeans.logs;

import SessionBeans.actions.OperationTypeEnum;
import entities.File;
import entities.FileChangeLog;
import entities.OperationType;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author Tomas
 */
@Stateless
@LocalBean
public class FileChangeLogService {
    
    @EJB
    private OperatioTypeSessionBean operatioTypeSessionBean;
    @PersistenceContext(unitName = "tCloudEE-ejbPU")
    private EntityManager em;

    public void addLogRow(Long userId, File file, OperationTypeEnum operationType) {
        OperationType loadOperationType = operatioTypeSessionBean.load(operationType);
        
        FileChangeLog log = new FileChangeLog(new Date(), file.getFileName(), file.getId(), loadOperationType, userId);
        
        em.merge(log);
        em.flush();
    }

    public List<FileChangeLog> loadAllChanges(File file){
        TypedQuery<FileChangeLog> createQuery = em.createQuery("Select OBJECT(u) from FileChangeLog u where u.fileId = '" + file.getId() + "' order by changeDate desc", FileChangeLog.class);
        List<FileChangeLog> resultList = createQuery.getResultList();
        
        return resultList;
    }
    
    public FileChangeLog loadLastChange(File file){
        return loadAllChanges(file).get(0);
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
    
}
